package game.states
{
	import flash.events.Event;
	import game.manager.ConfigurationManager;
	import game.manager.MapManager;
	import game.manager.TemplateTileManager;
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class InitializingState extends StateBase
	{
		
		public function InitializingState(stateMachine:StateMachine)
		{
			super(stateMachine);
		}
		
		override public function start():void
		{
			SplashScreen.instance.numSteps = 3;
			
			ConfigurationManager.instance.addEventListener(Event.COMPLETE, onConfigLoaded);
			ConfigurationManager.instance.loadAll(ConfigurationManager.CONFIG_URL);
		}
		
		override public function end():void
		{
		}
		
		/**
		 * конфиг загружен успешно
		 */ 
		public function onConfigLoaded(e:Event):void
		{
			SplashScreen.instance.nextStep();
			
			ConfigurationManager.instance.removeEventListener(Event.COMPLETE, onConfigLoaded);
			
			TemplateTileManager.instance.addEventListener(Event.COMPLETE, onLoadCompleted);
			TemplateTileManager.instance.loadAll(ConfigurationManager.instance.tileDataUrl);
			
			MapManager.instance.addEventListener(Event.COMPLETE, onLoadCompleted);
			MapManager.instance.loadAll(ConfigurationManager.instance.mapDataUrl);;
		}
		
		public function onLoadCompleted(e:Event):void
		{
			SplashScreen.instance.nextStep();
			
			var done:Boolean = false;
			done = TemplateTileManager.instance.loaded;
			done &&= MapManager.instance.loaded;
			
			if (done)
			{
				TemplateTileManager.instance.removeEventListener(Event.COMPLETE, onLoadCompleted);
				MapManager.instance.removeEventListener(Event.COMPLETE, onLoadCompleted);
				
				var state:StateBase = new InGameState(_stateMachine);
				_stateMachine.changeState(state);
			}
		}
	}
}